package com.insmess.speech.service.impl;

import com.insmess.speech.dto.TtsParamDto;
import com.insmess.speech.sdk.dto.TtsRequestDto;
import com.insmess.speech.sdk.dto.TtsResponseDto;
import com.insmess.speech.sdk.template.InsmessTtsTemplate;
import com.insmess.speech.sdk.util.FileBase64Utils;
import com.insmess.speech.service.TtsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.UUID;

@Service
public class TtsServiceImpl implements TtsService {
    @Autowired
    private InsmessTtsTemplate insmessTtsTemplate;

    @Override
    public File tts(String text) {
        TtsParamDto ttsParamDto = new TtsParamDto();
        ttsParamDto.setText(text);
        return tts(ttsParamDto);
    }

    @Override
    public File tts(TtsParamDto ttsParamDto) {
        String wavBase64 = ttsBase64(ttsParamDto);
        File tmpWavFile = new File("./tmp/" + UUID.randomUUID() + ".wav");
        FileBase64Utils.convertBase64ToFile(wavBase64, tmpWavFile.getPath());
        return tmpWavFile;
    }

    @Override
    public String ttsBase64(TtsParamDto ttsParamDto) {
        TtsRequestDto ttsRequestDto = new TtsRequestDto();
        ttsRequestDto.setText(ttsParamDto.getText());
        ttsRequestDto.setVolume(ttsParamDto.getVolume());
        ttsRequestDto.setSpeed(ttsParamDto.getSpeed());
        TtsResponseDto ttsResponseDto = insmessTtsTemplate.ttsRequest(ttsRequestDto);
        return ttsResponseDto.getResult().getAudio();
    }

    @Override
    public String ttsBase64(String text) {
        TtsParamDto ttsParamDto = new TtsParamDto();
        ttsParamDto.setText(text);
        return ttsBase64(ttsParamDto);
    }
}
